package com.qingke.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/SessionTest")
public class SessionTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SessionTest() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		//SESSION
		//创建和得到session，能够通过单例来保存一个用户的数据，可多次访问
		//将servies注释掉后可看到效果
		response.getWriter().append("Served at: ").append(request.getContextPath()+"\n");
		//参数为false:之前不存在也不创建 为true:之前不存在就创建一个  参数为空相当于true
		HttpSession hs = request.getSession(false);
		ArrayList<Integer> arrayList = new ArrayList<>();
		arrayList.add(1);
		arrayList.add(2);
		arrayList.add(3);
		if(hs==null){
			response.getWriter().append("no session yet,create it\n");
			hs = request.getSession(true);
			//session过期时间，默认1800s -1为不过期,知道浏览器关闭
			hs.setMaxInactiveInterval(-1);
			//可以存任何对象
			hs.setAttribute("key1", arrayList);
			response.getWriter().append("session created,and set attribute to session\n");
		}else {			
			response.getWriter().append("session already existed\n");
			@SuppressWarnings("unchecked")
			ArrayList<Integer> result = (ArrayList<Integer>) hs.getAttribute("key1");
			for (Integer integer : result) {
				response.getWriter().append("i="+integer+"\r\n");
			}
		}
		response.getWriter().append("session id is:"+hs.getId()+"");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
